<script>
import parentChart from "./chart";
import color from "./config/color";
import grid from "./config/grid";
import valueAxis from "./config/valueAxis";
import categoryAxis from "./config/categoryAxis";
import barSeries from "./config/barSeries";
export default {
  name: "app-bar-chart",
  extends: parentChart,
  data() {
    return {};
  },
  methods: {
    /**
     * 父类 mounted方法 和 watch data 都自动进行调用
     * @param chart echart实例
     */
    createChart(chart) {
      if (!chart) return;
      // 判断数据
      this.emptyData = false;
      if (!this.data || !this.data.length) {
        return (this.emptyData = true);
      }
      const defaultOptions = {
        grid: grid,
        tooltip: {
          show: true
        },
        yAxis: valueAxis,
        color: color
      };
      // 克隆
      let options = JSON.parse(JSON.stringify(defaultOptions));

      // 设置x轴
      this.setXAxis(options);
      // 设置数据
      this.setSeries(options);

      // 绘制chart (调用父类的render函数)
      this.render(options);
    },
    setXAxis(options) {
      const xAxis = JSON.parse(JSON.stringify(categoryAxis));
      xAxis.data = this.getCategories();
      options.xAxis = xAxis;
    },
    getCategories() {
      let data = [];
      if (Array.isArray(this.data) && this.data.length) {
        data = this.data[0].data.map(d => d.name);
      }
      return data;
    },
    setSeries(options) {
      if (Array.isArray(this.data)) {
        options.series = this.data.map(d => {
          const s = JSON.parse(JSON.stringify(barSeries));
          s.data = d.data;
          s.name = d.name;
          return s;
        });
      }
    }
  }
};
</script>
